import sys
import rasterio
from rasterio.plot import show
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog, QLabel, QVBoxLayout,QLineEdit
from PyQt5.QtGui import QPixmap
from io import BytesIO
from PIL import Image
import numpy as np


def show_file_dialog():
    app = QApplication(sys.argv)
    window = QWidget()

    # 整体布局
    layout = QVBoxLayout()

    # 用于显示文件路径的文本框
    file_path_edit = QLineEdit(window)
    layout.addWidget(file_path_edit)

    # 用于显示遥感影像的标签
    image_label = QLabel(window)
    layout.addWidget(image_label)

    # 触发文件选择操作的按钮
    choose_file_button = QPushButton('Choose Image', window)

    def handle_button_click():
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(window, "Select Image", ".", "Images (*.png *.jpg *.jpeg);;GeoTIFF Files (*.tif *.tiff);;All Files (*)", options=options)
        if file_name:
            file_path_edit.setText(file_name)
            try:
                # 使用rasterio打开遥感影像
                with rasterio.open(file_name) as src:
                    # 读取RGB三个波段的数据（假设影像有这三个波段，可根据实际调整）
                    r_band = src.read(1)
                    g_band = src.read(2)
                    b_band = src.read(3)
                    # 将各波段数据转换为合适的格式用于显示（这里简单处理为8位无符号整数）
                    # 注意：这只是一个简单的转换示例，实际可能需要更复杂的处理
                    r_band = ((r_band - r_band.min()) * (255.0 / (r_band.max() - r_band.min()))).astype('uint8')
                    g_band = ((g_band - g_band.min()) * (255.0 / (g_band.max() - g_band.min()))).astype('uint8')
                    b_band = ((b_band - b_band.min()) * (255.0 / (b_band.max() - b_band.min()))).astype('uint8')
                    # 合并RGB三个波段数据为一个三维数组，用于构建彩色图像
                    img_data = np.dstack((r_band, g_band, b_band))
                    # 使用PIL将数组转换为图像对象
                    img = Image.fromarray(img_data, 'RGB')
                    # 将图像对象保存到内存文件对象中
                    output = BytesIO()
                    img.save(output, 'PNG')
                    output.seek(0)
                    # 使用QPixmap加载内存中的图像数据并设置到标签上
                    pixmap = QPixmap()
                    pixmap.loadFromData(output.read())
                    image_label.setPixmap(pixmap.scaled(image_label.size(), aspectRatioMode=1))
            except Exception as e:
                print(f"Error opening or processing the file: {e}")

    choose_file_button.clicked.connect(handle_button_click)
    layout.addWidget(choose_file_button)

    window.setLayout(layout)
    window.setGeometry(300, 50, 800, 600)
    window.setWindowTitle('Remote Sensing Image Viewer')
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    show_file_dialog()